#pragma once

#include <iostream>
#include <string>
#include <cstring>
#include <cerrno>
#include <cassert>
#include <unistd.h>
#include <signal.h>
#include <pthread.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "Log.hpp"
#include <memory>
#include "ThreadPool.hpp"
#include "Task.hpp"


#define SIZE 1024

static void Service(int sock, const std::string& clientIP, uint16_t clientPort, const std::string& threadName)
{
    // Echo Server
    char buffer[SIZE];
    while(true)
    {
        ssize_t s = read(sock, buffer, sizeof(buffer) - 1);
        if(s > 0)
        {
            buffer[s] = '\0';
            std::cout << threadName << " | " << clientIP << " : " << clientPort << "#" << buffer << std::endl;
        }
        else if(s == 0) // 对端关闭连接
        {
            logMessage(NORMAL, "%s:%d quit, me too!", clientIP.c_str(), clientPort);
            break;
        }
        else
        {
            logMessage(FATAL, "Read Fail, Errno:%d, Strerror:%s", errno, strerror(errno));
            break;
        }
        // 将消息发回去
        write(sock, buffer, strlen(buffer));
    }
    close(sock);
}

class TcpServer
{
private:
    const static int backlog = 20; // 全队列长度
public:
    TcpServer(uint16_t port, std::string ip = "")
        : _port(port)
        , _ip(ip)
        , _listenSock(-1)
        , _ptr(ThreadPool<Task>::getThreadPool())
    {}

    void InitServer()
    {
        // 1. 创建套接字
        _listenSock = socket(AF_INET, SOCK_STREAM, 0);
        if(_listenSock < 0)
        {
            logMessage(FATAL, "Create Socket Fail! Errno:%d Strerror:%s", errno, strerror(errno));
            exit(2);
        }
        logMessage(NORMAL, "Create Socket Success! _sock:%d", _listenSock);

        // 2. 绑定套接字
        struct sockaddr_in local;
        memset(&local, 0, sizeof local);
        local.sin_family = AF_INET;
        local.sin_addr.s_addr = _ip.empty() ? INADDR_ANY : inet_addr(_ip.c_str());
        local.sin_port = htons(_port);
        if(bind(_listenSock, (struct sockaddr*)&local, sizeof(local)) < 0)
        {
            logMessage(FATAL, "Bind Socket Fail! Errno:%d Strerror:%s", errno, strerror(errno));
            exit(3);
        }

        // 3. 因为TCP是面向连接的,那么正式进行网络通信时,先需要建立连接
        if(listen(_listenSock, backlog) < 0)
        {
            logMessage(FATAL, "Listen Socket Fail! Errno:%d Strerrno:%s", errno, strerror(errno));
            exit(4);
        }
        logMessage(NORMAL, "Init Server Success!");
    }

    void StartServer()
    {
        _ptr->Run();
        while(true)
        {
            // 4. 获取连接
            struct sockaddr_in src;
            socklen_t len = sizeof(src);
            // accept函数的返回值是文件描述符,它用于后续的网络通信
            // 而_sock只用于获取新连接,并不用于后续的网络通信
            // 注：accept是阻塞等待新连接的到来
            int serviceSock = accept(_listenSock, (struct sockaddr*)&src, &len);
            if(serviceSock < 0)
            {
                logMessage(ERROR, "Accept FAIL, Errno:%d Strerrno:%s", errno, strerror(errno));
                continue;
            }
            // 获取连接成功,开始进行网络通信
            uint16_t clientPort = ntohs(src.sin_port);
            std::string clientIP = inet_ntoa(src.sin_addr);
            logMessage(NORMAL, "Link Success! serviceSock:%d clientIP:%s clientPort:%d", serviceSock, clientIP.c_str(), clientPort);
            Task t(serviceSock, clientIP, clientPort, Service);
            _ptr->Push(t);
        }
    }

    ~TcpServer()
    {
        if(_listenSock >= 0)
            close(_listenSock);
    }

private:
    uint16_t _port;
    std::string _ip;
    int _listenSock;
    std::unique_ptr<ThreadPool<Task>> _ptr;
};